package com.gamatechno.solodestination;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.facebook.android.Facebook;
import com.facebook.android.SessionStore;
import com.gamatechno.adapter.ImageLoader;
import com.gamatechno.adapter.NavDrawerListAdapter;
import com.gamatechno.solodestination.model.AppPreferences;
import com.gamatechno.solodestination.model.HttpUtils;
import com.gamatechno.solodestination.model.Komentar;
import com.gamatechno.solodestination.model.NavDrawerItem;
import com.gamatechno.solodestination.util.Utils;
import com.google.android.gms.gcm.GoogleCloudMessaging;

import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;

import android.app.FragmentManager;
import android.app.SearchManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	private DrawerLayout mDrawerLayout;
	private ListView mDrawerList;
	private ActionBarDrawerToggle mDrawerToggle;
	HashMap<String, String> params;
	TextView tvSuhunow;
	// nav drawer title
	private CharSequence mDrawerTitle;

	// used to store app title
	// private CharSequence mTitle;

	// slide menu items
	private String[] navMenuTitles;
	private TypedArray navMenuIcons;

	private ArrayList<NavDrawerItem> navDrawerItems;
	private NavDrawerListAdapter adapter;

	private static final String APP_ID = "239419142913008";
	private static final String SENDER_ID_GCM = "204153616086";
	private static final String URL_REGISTER = "http://sms.gamatechno.com/solo_destination/services/getRef.php";

	private Facebook mFacebook;
	String name_user = "";

	GoogleCloudMessaging gcm;
	String gcm_id;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		// Instansiasi GCM

		if (gcm == null) {
			gcm = GoogleCloudMessaging.getInstance(this);
		}

		params = new HashMap<String, String>();

		// CEK JARINGAN, JIKA CONNECT MAKA REGISTER GCM
		if (Utils.isConnectedToInternet(this)) {
			Utils.TRACE("solodest", "ada koneksi");
			if (!Utils.getDataBooleanFromSP(this, Utils.IS_GCM_REG)) {
				Utils.TRACE("SOLOBUG", "request gcm");
				new AsyncGCM().execute();
			}

		}

		Log.i("APP_ID", APP_ID + "");
		mFacebook = new Facebook(APP_ID);
		SessionStore.restore(mFacebook, this);
		name_user = SessionStore.getName(this);
		Log.wtf("mfacebook.isSessionValid()", mFacebook.isSessionValid() + "");

		Bitmap b = BitmapFactory.decodeResource(getResources(),
				R.drawable.header_img);
		BitmapDrawable bd = new BitmapDrawable(getResources(), b);
		ActionBar ab = getActionBar();
		ab.setBackgroundDrawable(bd);
		LayoutInflater inflater = (LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View v = inflater.inflate(R.layout.actionbar_logo, null);
		ab.setCustomView(v);
		ab.setDisplayShowCustomEnabled(true);

		// mTitle = mDrawerTitle = getTitle();
		// load slide menu items
		navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

		// nav drawer icons from resources
		navMenuIcons = getResources()
				.obtainTypedArray(R.array.nav_drawer_icons);

		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerList = (ListView) findViewById(R.id.list_slidermenu);

		navDrawerItems = new ArrayList<NavDrawerItem>();

		// adding nav drawer items to array
		// Navigation item
		LayoutInflater inflatez = (LayoutInflater) this
				.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
		View convertView = inflatez.inflate(R.layout.drawer_header, null);

		mDrawerList.addHeaderView(convertView);
		navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons
				.getResourceId(1, -1)));
		navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons
				.getResourceId(2, -1)));
		navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons
				.getResourceId(3, -1)));
		navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons
				.getResourceId(4, -1)));

		// Recycle the typed array
		navMenuIcons.recycle();

		mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

		// setting the nav drawer list adapter
		adapter = new NavDrawerListAdapter(getApplicationContext(),
				navDrawerItems);
		mDrawerList.setAdapter(adapter);

		// enabling action bar app icon and behaving it as toggle button
		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setHomeButtonEnabled(true);
		getActionBar().setLogo(R.drawable.ic_home);
		mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
				R.drawable.ic_drawer, // nav menu toggle icon
				0, // nav drawer open - description for
					// accessibility
				0 // nav drawer close - description for
					// accessibility
		) {
			public void onDrawerClosed(View view) {
				// getActionBar().setTitle(mTitle);
				// calling onPrepareOptionsMenu() to show action bar icons
				invalidateOptionsMenu();
			}

			public void onDrawerOpened(View drawerView) {
				// getActionBar().setTitle(mDrawerTitle);
				// calling onPrepareOptionsMenu() to hide action bar icons
				LinearLayout ll_connect = (LinearLayout) drawerView
						.findViewById(R.id.drawer_connected);
				TextView ll_disconnect = (TextView) drawerView
						.findViewById(R.id.drawer_disconnected);
				ImageView drawer_img = (ImageView) drawerView
						.findViewById(R.id.drawer_img);
				TextView drawer_name = (TextView) drawerView
						.findViewById(R.id.drawer_name);

				Toast.makeText(MainActivity.this, "opened", Toast.LENGTH_SHORT)
						.show();
				// mFacebook = new Facebook(APP_ID);

				drawer_name.setText(name_user);

				new SetPP().execute();

				if (mFacebook.isSessionValid()) {
					ll_connect.setVisibility(View.VISIBLE);
					ll_disconnect.setVisibility(View.GONE);
				} else {
					ll_connect.setVisibility(View.GONE);
					ll_disconnect.setVisibility(View.VISIBLE);
				}
				ll_disconnect.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
					}
				});

				invalidateOptionsMenu();
			}
		};
		mDrawerLayout.setDrawerListener(mDrawerToggle);

		if (savedInstanceState == null) {
			// on first time display view for first nav item
			displayView(0);
		}
	}

	public void setimg(String result) {
		ImageLoader imgloader = new ImageLoader(MainActivity.this);
		ImageView drawer_img = (ImageView) findViewById(R.id.drawer_img);
		imgloader.DisplayImage(result, drawer_img);

	}

	// ASYNC REGISTER GCM
	private class AsyncGCM extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			try {
				Utils.TRACE("SOLOBUG", "rikues gcm");
				gcm_id = gcm.register(SENDER_ID_GCM);
				Utils.TRACE("SOLOBUG", "ini gcm : " + gcm_id);

			} catch (Exception e) {
				// TODO: handle exception
				Utils.TRACE("SOLOBUG", e.getMessage());
			}

			return null;
		}

		// kirim gcm ke server
		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			registerGCM(URL_REGISTER);
			Utils.TRACE("SOLOBUG", "hasil gcm : " + gcm_id);
		}

	}

	private void registerGCM(String urlRegister) {
		// TODO Auto-generated method stub
		StringRequest request = new StringRequest(Request.Method.POST,
				urlRegister, new Response.Listener<String>() {

					@Override
					public void onResponse(String arg0) {
						// TODO Auto-generated method stub
						try {
							JSONObject obj = new JSONObject(arg0);
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}

				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError arg0) {
						// TODO Auto-generated method stub

					}

				}) {
			@Override
			protected Map<String, String> getParams() throws AuthFailureError {
				// TODO Auto-generated method stub
				params.put("method", "reg");
				params.put("format", "json");
				params.put("reg", gcm_id);

				return params;
			}

		};

		// muncul dialog
		BaseApplication.getInstance().addToRequestQueue(request, "Main");
	}

	class SetPP extends AsyncTask<Void, Void, String> {

		@Override
		protected String doInBackground(Void... params) {
			AppPreferences _pref = new AppPreferences(MainActivity.this);
			HttpUtils u = new HttpUtils();
			String imgz = "";
			try {

				String urlImg = "https://graph.facebook.com/" + _pref.getIdFb()
						+ "?fields=picture";
				Log.wtf("urlImg", urlImg);

				String content_urlImg = u.getContents(urlImg);
				Log.wtf("content_urlImg", content_urlImg);

				JSONObject jobImg = new JSONObject(content_urlImg);
				JSONObject jobImg2 = jobImg.getJSONObject("picture");
				JSONObject jobImg3 = jobImg2.getJSONObject("data");
				imgz = jobImg3.getString("url");

			} catch (JSONException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

			return imgz;

		}

		@Override
		protected void onPostExecute(String result) {

			setimg(result);
			// super.onPostExecute(result);
		}
	}

	/**
	 * Slide menu item click listener
	 * */
	private class SlideMenuClickListener implements
			ListView.OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// display view for selected nav drawer item
			displayView(position);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main, menu);

		// // Associate searchable configuration with the SearchView
		// SearchManager searchManager = (SearchManager)
		// getSystemService(Context.SEARCH_SERVICE);
		// SearchView searchView = (SearchView)
		// menu.findItem(R.id.action_search)
		// .getActionView();
		// searchView.setSearchableInfo(searchManager
		// .getSearchableInfo(getComponentName()));

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// toggle nav drawer on selecting action bar app icon/title
		if (mDrawerToggle.onOptionsItemSelected(item)) {
			return true;
		}
		// Handle action bar actions click
		switch (item.getItemId()) {
		case R.id.action_search:
			Intent j = new Intent(this, SearchActivity.class);
			startActivity(j);
			break;
		default:
			return super.onOptionsItemSelected(item);
		}
		return true;
	}

	/* *
	 * Called when invalidateOptionsMenu() is triggered
	 */
	// @Override
	// public boolean onPrepareOptionsMenu(Menu menu) {
	// // if nav drawer is opened, hide the action items
	// SearchView mSearch = (SearchView) menu.findItem(R.id.action_search)
	// .getActionView();
	// int searchimg = getResources().getIdentifier(
	// "android:id/search_button", null, null);
	// ImageView v = (ImageView) mSearch.findViewById(searchimg);
	// v.setImageResource(R.drawable.search_menu);
	// //boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
	// menu.findItem(R.id.action_search).setVisible(true);
	// return super.onPrepareOptionsMenu(menu);
	// }

	/**
	 * Diplaying fragment view for selected nav drawer list item
	 * */
	private void displayView(int position) {
		// update the main content by replacing fragments
		android.app.Fragment fragment = null;
		switch (position) {
		case 0:
			fragment = new HomeFragment();
			break;
		case 1:
			fragment = new FovoriteFragment();
			break;
		case 2:
			fragment = new JournalPerjalananFragment();
			break;
		case 3:
			fragment = new NotifikasiFragment();
			break;
		case 4:
			Intent j = new Intent(this, PengaturanFragment.class);
			startActivity(j);
			break;
		default:
			break;
		}

		if (fragment != null) {
			FragmentManager fragmentManager = getFragmentManager();
			fragmentManager.beginTransaction()
					.replace(R.id.frame_container, fragment)
					.addToBackStack("fragBack").commit();

			// update selected item and title, then close the drawer
			mDrawerList.setItemChecked(position, true);
			mDrawerList.setSelection(position);
			setTitle(navMenuTitles[position]);
			mDrawerLayout.closeDrawer(mDrawerList);
			switch (position) {
			case 0:
				tvSuhunow = (TextView) findViewById(R.id.suhuNow);

				break;

			default:
				break;
			}
		} else {
			// error in creating fragment
			Log.e("MainActivity", "Error in creating fragment");
		}
	}

	@Override
	public void setTitle(CharSequence title) {
		// mTitle = title;
		getActionBar().setTitle("");
	}

	/**
	 * When using the ActionBarDrawerToggle, you must call it during
	 * onPostCreate() and onConfigurationChanged()...
	 */

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Sync the toggle state after onRestoreInstanceState has occurred.
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// Pass any configuration change to the drawer toggls
		mDrawerToggle.onConfigurationChanged(newConfig);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		FragmentManager frManager = getFragmentManager();
		Log.d("tes", String.valueOf(frManager
				.findFragmentById(R.id.frame_container)));
		android.app.Fragment fr = frManager
				.findFragmentById(R.id.frame_container);
		if (fr.toString().contains("HomeFragment"))
			if ((keyCode == KeyEvent.KEYCODE_BACK)) {
				LayoutInflater inflater = (LayoutInflater) getLayoutInflater();
				final View header = inflater.inflate(
						R.layout.dialog_customtitle, null);

				TextView tx = (TextView) header.findViewById(R.id.text_title);
				tx.setText("Exit ?");
				new AlertDialog.Builder(MainActivity.this)
						.setCustomTitle(header)
						.setMessage("Apakah anda yakin akan keluar?")
						.setPositiveButton("Ya",
								new DialogInterface.OnClickListener() {
									@TargetApi(11)
									public void onClick(DialogInterface dialog,
											int id) {
										finish();
									}
								})
						.setNegativeButton("Tidak",
								new DialogInterface.OnClickListener() {
									@TargetApi(11)
									public void onClick(DialogInterface dialog,
											int id) {
										dialog.cancel();
									}
								}).show();
			}
		return super.onKeyDown(keyCode, event);
	}

}
